package com.xiaoc.bulldozer.controller;

import com.google.common.collect.Maps;
import com.xc.framework.cache.manager.CacheManager;
import com.xc.framework.cache.utils.CacheUtils;
import com.xc.framework.common.page.PageDto;
import com.xiaoc.bulldozer.annotate.Duplicate;
import com.xiaoc.bulldozer.common.CacheKeys;
import com.xiaoc.bulldozer.common.Constant;
import com.xiaoc.bulldozer.common.ResponseCode;
import com.xiaoc.bulldozer.common.dto.AccountDto;
import com.xiaoc.bulldozer.common.dto.AccountQueryDto;
import com.xiaoc.bulldozer.common.dto.WeixinUserDto;
import com.xiaoc.bulldozer.common.dto.WxPhoneNumber;
import com.xiaoc.bulldozer.common.model.Account;
import com.xiaoc.bulldozer.common.service.AccountService;
import com.xiaoc.bulldozer.common.service.SmtpMessageService;
import com.xiaoc.bulldozer.common.util.DataUtil;
import com.xiaoc.bulldozer.facade.AccountBalanceFacade;
import com.xiaoc.bulldozer.facade.AwardPartnerFacade;
import com.xiaoc.bulldozer.service.WxService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * describe:
 *
 * @author lihuancheng
 * @date 2018/8/29
 */
@Controller
@RequestMapping(value = "/account")
public class AccountController extends BulldozerFrontBaseController {

    private Logger logger = LoggerFactory.getLogger(AccountController.class);

    @Resource(name = "smtpMessageService")
    private SmtpMessageService smtpMessageService;

    @Resource(name = "remoteCacheManager")
    private CacheManager remoteCacheManager;

    @Resource(name = "awardPartnerFacade")
    private AwardPartnerFacade awardPartnerFacade;


    @Resource(name = "accountService")
    private AccountService accountService;


    @Resource(name = "wxService")
    private WxService wxService;

    /**
     * 我的账户-初始化
     */
    @RequestMapping(value = "/init")
    public ModelAndView init() {
        WeixinUserDto weixinUserDto = getCurrentWeixinUserDto();
        Integer userId = weixinUserDto.getId();
        return renderJson("account/init.json", Maps.newHashMap());
    }

    /**
     * 账户信息
     */
    @RequestMapping(value = "/info")
    public ModelAndView info() {
        WeixinUserDto weixinUserDto = getCurrentWeixinUserDto();
        Integer userId = weixinUserDto.getId();

        Account account = null;
       /* try {
            account = accountFacade.getAccountByUserId(userId);
        } catch (Exception e) {
            logger.error("info error", e);
            throw new BusinessException(ResponseCode.BUSINESS_ERROR.getCode(), "异常user_id" + weixinUserDto.getId());
        }
*/
        if (account == null) {
            logger.error("该用户尚未注册");
            return jsonFailed(ResponseCode.BUSINESS_ERROR.getCode(), "该用户尚未注册");
        }

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("account", account);
        return renderJson("account/info.json", paramMap);
    }


    @Duplicate
    @PostMapping(value = "/register")
    public ModelAndView register(@RequestBody AccountDto accountDto) throws Exception {
        logger.info("account register params:{}", accountDto);

        WeixinUserDto weixinUserDto = getCurrentWeixinUserDto();

        String  phoneNumber = accountDto.getPhoneNumber();
        if (phoneNumber == null || phoneNumber.isEmpty()) {
            return jsonFailed(ResponseCode.REQUESTBODY_ERROR.getCode(), ResponseCode.REQUESTBODY_ERROR.getMsg());
        }

        //短信验证码
        boolean checkCode = smtpMessageService.verifyCode(phoneNumber, accountDto.getCode(),Constant.CODE_TYPE.REGISTER);
        if (!checkCode) {
            return jsonFailed(ResponseCode.VERIFY_FAIL.getCode(), "验证码错误");
        }

        remoteCacheManager.remove(CacheUtils.generateCacheKey(CacheKeys.PARENT_USER_ID_KEY, weixinUserDto.getId()));
        smtpMessageService.clearVerifyCode(accountDto.getPhoneNumber());
        return jsonSucess();
    }

    @Duplicate
    @PostMapping(value = "/wxRegister")
    public ModelAndView wxRegister(@RequestBody WxPhoneNumber wxPhoneNumber){

        String phoneNumber = null;
        try {

            logger.info("getCurrentWeixinUserDto()：{}",getCurrentWeixinUserDto().getSessionKey());
            phoneNumber = wxService.getPhoneNumber(getCurrentWeixinUserDto(),wxPhoneNumber.getEncryptedData(),wxPhoneNumber.getIv());
        } catch (Exception e) {
            logger.error("微信注册失败", e);
            return jsonFailed(ResponseCode.BUSINESS_ERROR.getCode(), "可选择输入手机号注册");
        }

        WeixinUserDto weixinUserDto = getCurrentWeixinUserDto();

        if (phoneNumber == null || phoneNumber.isEmpty()) {
            logger.info("微信注册手机号为空");
            return jsonFailed(ResponseCode.REQUESTBODY_ERROR.getCode(), ResponseCode.REQUESTBODY_ERROR.getMsg());
        }

        Account account = accountService.getAccountByPhoneNumber(phoneNumber);

        if (account != null) {
            logger.info("微信注册用户已注册");
            return jsonFailed(ResponseCode.VERIFY_SUCCESS.getCode(), ResponseCode.VERIFY_SUCCESS.getMsg());
        }

        AccountDto accountDto = new AccountDto();
        if (wxPhoneNumber.getParentUserId() != null) {
            logger.info("推荐人id[{}]",wxPhoneNumber.getParentUserId());
            accountDto.setParentUserId(wxPhoneNumber.getParentUserId());
        }

        accountDto.setPhoneNumber(phoneNumber);
        return jsonSucess();
    }

    @GetMapping(value = "/registerList")
    public ModelAndView registerList(AccountQueryDto queryDto){

        WeixinUserDto weixinUserDto = getCurrentWeixinUserDto();
        Account account = accountService.getAccountByUserId(weixinUserDto.getId());

        if (account == null) {
            logger.info("用户为注册");
            return jsonFailed(ResponseCode.BUSINESS_ERROR.getCode(), "请先注册");
        }

        if(account.getType() != Constant.ACCOUNT_TYPE.MANAGER){
            logger.info("您不是渠道经理。");
            return jsonFailed(ResponseCode.BUSINESS_ERROR.getCode(), "您不是渠道经理。");
        }

        Map<String, Object> params = new HashMap<>();
        queryDto.setId(account.getId());
        int count = accountService.getAccountCountByOwnerId(queryDto.getId());
        if (count > 0) {
            List<Account> accountList = accountService.getAccountListByOwnerId(queryDto);
            accountList.forEach(account1->{
                account1.setPhoneNumber(DataUtil.hidePhoneNumber(account1.getPhoneNumber()));
                account1.setName(DataUtil.hideName(account1.getName()));
            });
            params.put("accountList", accountList);
        }
        PageDto pageDto = new PageDto(queryDto.getPage(), count, PageDto.PAGE_SIZE);
        params.put("pageDto", pageDto);

        return renderJson("account/accountList.json", params);
    }

    @GetMapping(value = "/registerCount")
    public ModelAndView registerCount(){

        WeixinUserDto weixinUserDto = getCurrentWeixinUserDto();
        Account account = accountService.getAccountByUserId(weixinUserDto.getId());

        if (account == null) {
            logger.info("请先注册。");
            return jsonFailed(ResponseCode.BUSINESS_ERROR.getCode(), "请先注册");
        }

        if(account.getType() != Constant.ACCOUNT_TYPE.MANAGER){
            logger.info("您不是渠道经理。");
            return jsonFailed(ResponseCode.BUSINESS_ERROR.getCode(), "您不是渠道经理。");
        }

        int count = accountService.getAccountCountByOwnerId(account.getId());
        Map<String, Object> params = new HashMap<>();
        params.put("totalCount", count);
        return renderJson("account/accountCount.json", params);
    }

}
